package net.lainiao.zhihu.backserver;

import net.lainiao.zhihu.common.Common;
import net.lainiao.zhihu.dao.ZhihuhuatiMapper;
import net.lainiao.zhihu.dao.ZhihuhuatipageMapper;
import net.lainiao.zhihu.model.Zhihuhuati;
import net.lainiao.zhihu.model.Zhihuhuatipage;
import org.springframework.context.ApplicationContext;
import net.lainiao.zhihu.reptitle.ZhihuCollect;

/**
 * Created by Administrator on 2016/1/15.
 */
public class ZhihuhuatiTask extends ZhihuTask implements Runnable {
    public ZhihuhuatiTask(ApplicationContext context) {
        super(context);
    }
    public void run() {
        System.out.println("知乎话题服务开启");
        ZhihuhuatiMapper zhihuhuatiMapper = context.getBean(ZhihuhuatiMapper.class);
        ZhihuhuatipageMapper zhihuhuatipageMapper = context.getBean(ZhihuhuatipageMapper.class);
        Zhihuhuati zhihuhuati=null;
        while (status == 1) {
            try {
                zhihuhuati = zhihuhuatiMapper.getNext();
                if (zhihuhuati == null) {
                    System.out.println("不存在可以爬的!");
                    break;
                }
                String url = zhihuhuati.getUrl();
                int max = ZhihuCollect.getMax(url);
                for (int i = 1; i <= max; i++) {
                    Zhihuhuatipage page = new Zhihuhuatipage();
                    String urlt = url + "?page=" + i;
                    page.setId(Common.getNewUUID());
                    page.setUrl(urlt);
                    page.setZzhtId(zhihuhuati.getId());
                    page.setStatus(0);
                    zhihuhuatipageMapper.insert(page);
                    Thread.sleep(500);
                }
                zhihuhuati.setStatus(1);
                zhihuhuatiMapper.updateByPrimaryKey(zhihuhuati);
            } catch (Exception e) {
                e.printStackTrace();
                if(zhihuhuati!=null){
                    zhihuhuati.setStatus(2);
                    zhihuhuatiMapper.updateByPrimaryKey(zhihuhuati);
                }
            }
        }
        System.out.println("知乎话题服务关闭");
    }
}
